package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.lkd.common.VMSystem;
import com.lkd.dao.TaskCollectDao;
import com.lkd.dao.TaskDao;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.entity.TaskStatusTypeEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskReportInfoVO;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.service.TaskStatusTypeService;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao,TaskEntity> implements TaskService{

    @Autowired
    private TaskStatusTypeService statusTypeService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private VMService vmService;

    @Autowired
    private UserService userService;

    @Autowired
    private TaskDetailsService taskDetailsService;

    @Autowired
    private TaskDao taskDao;

    @Autowired
    private TaskCollectDao taskCollectDao;

    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex,pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if(!Strings.isNullOrEmpty(innerCode)){
            qw.eq(TaskEntity::getInnerCode,innerCode);
        }
        if(userId != null && userId > 0){
            qw.eq(TaskEntity::getUserId,userId);
        }
        if(!Strings.isNullOrEmpty(taskCode)){
            qw.like(TaskEntity::getTaskCode,taskCode);
        }
        if(status != null && status > 0){
            qw.eq(TaskEntity::getTaskStatus,status);
        }
        if(isRepair != null){
            if(isRepair){
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }else {
                qw.eq(TaskEntity::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if(!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)){
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime,LocalDate.parse(end,DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page,qw));
    }



    @Override
    public List<TaskStatusTypeEntity> getAllStatus() {
        QueryWrapper<TaskStatusTypeEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .ge(TaskStatusTypeEntity::getStatusId,VMSystem.TASK_STATUS_CREATE);

        return statusTypeService.list(qw);
    }
    /**
     * 功能描述: 创建工单
     * @param taskViewModel
     * @return : boolean
     */
    @Transactional
    @Override
    public boolean createTask(TaskViewModel taskViewModel) throws LogicException {
        if(hasTask(taskViewModel.getInnerCode(),taskViewModel.getProductType())) {
            throw new LogicException("该机器有未完成的同类型工单");
        }

        //校验设备是否存下
        /*String innerCode = taskViewModel.getInnerCode();
        if(StringUtils.isBlank(innerCode)){
            throw new LogicException("该设备不存在");
        }*/
        //校验设备编号是否正确
       /* TaskEntity task = new TaskEntity();
        if (!innerCode.equals(task.getInnerCode())){
            throw new LogicException("该设备不存在");
        }*/
        //校验售货机状态
        //如果是投放工单,判断状态是否为运营
        /*if(taskViewModel.getProductType() == VMSystem.TASK_TYPE_DEPLOY){
            TaskTypeEntity taskTypeEntity = new TaskTypeEntity();
            if (taskTypeEntity.getType() == VMSystem.VM_STATUS_RUNNING){
                throw new LogicException("工单类型不匹配");
            }
        }
        if(taskViewModel.getProductType() == VMSystem.TASK_TYPE_SUPPLY){
            TaskTypeEntity taskTypeEntity = new TaskTypeEntity();
            if (taskTypeEntity.getType() != VMSystem.VM_STATUS_RUNNING){
                throw new LogicException("工单类型不匹配");
            }
        }
        if(taskViewModel.getProductType() == VMSystem.VM_STATUS_REVOKE){
            TaskTypeEntity taskTypeEntity = new TaskTypeEntity();
            if (taskTypeEntity.getType() != VMSystem.VM_STATUS_RUNNING){
                throw new LogicException("工单类型不匹配");
            }
        }*/

        //校验工单类型
        //校验指派人类型

        //判断"同一设备"是否存同一类型未完成的工单
        //根据订单编号查询售货机
        /*TaskEntity one = taskDao.selectById(innerCode);
        if (one == null) {
            throw new LogicException("该设备不存在");
        }*/

        //如果售货机的工单类型有一样的,就抛出异常   192.168.21.44
        //跨服务查询售货机微服务，得到售货机的地址和区域id
        VmVO vm = vmService.getVMInfo(taskViewModel.getInnerCode());
        if(vm==null){
            throw new LogicException("该机器不存在");
        }
        checkCreateTask(vm.getVmStatus(),taskViewModel.getProductType());//验证售货机状态
        //跨服务查询用户微服务，得到用户名(创建工单的人id)
        UserVO user = userService.getUser(taskViewModel.getUserId());
        if(user==null){
            throw new LogicException("该用户不存在");
        }
        //新增工单表记录
        TaskEntity taskEntity = new TaskEntity();
        taskEntity.setTaskCode(generateTaskCode());//工单编号
        BeanUtils.copyProperties(taskViewModel,taskEntity);//复制属性
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);//工单状态
        taskEntity.setProductTypeId(taskViewModel.getProductType());//工单类型

        taskEntity.setAddr(vm.getNodeAddr());//地址
        taskEntity.setRegionId(vm.getRegionId());//区域
        taskEntity.setUserName(user.getUserName());//用户名
        this.save(taskEntity);
        //如果是补货工单，向 工单明细表插入记录
        if(taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY){
            taskViewModel.getDetails().forEach(d->{
                TaskDetailsEntity detailsEntity = new TaskDetailsEntity();
                BeanUtils.copyProperties( d,detailsEntity );
                detailsEntity.setTaskId(taskEntity.getTaskId());
                taskDetailsService.save(detailsEntity);
            });
        }

        return true;
    }
    /**
     * 创建工单校验
     * @param vmStatus
     * @param productType
     * @throws LogicException
     */
    private void checkCreateTask(Integer vmStatus,int productType) throws LogicException {
        //如果是投放工单，状态为运营
        if(productType == VMSystem.TASK_TYPE_DEPLOY  && vmStatus == VMSystem.VM_STATUS_RUNNING){
            throw new LogicException("该设备已在运营");
        }

        //如果是补货工单，状态不是运营状态
        if(productType == VMSystem.TASK_TYPE_SUPPLY  && vmStatus != VMSystem.VM_STATUS_RUNNING){
            throw new LogicException("该设备不在运营状态");
        }

        //如果是撤机工单，状态不是运营状态
        if(productType == VMSystem.TASK_TYPE_REVOKE  && vmStatus != VMSystem.VM_STATUS_RUNNING){
            throw new LogicException("该设备不在运营状态");
        }
    }
    /**
     * 同一台设备下是否存在未完成的工单
     * @param innerCode
     * @param productionType
     * @return
     */
    private boolean hasTask(String innerCode,int productionType){
        QueryWrapper<TaskEntity> qw = new QueryWrapper<>();
        qw.lambda()
                .select(TaskEntity::getTaskId)
                .eq(TaskEntity::getInnerCode,innerCode)
                .eq(TaskEntity::getProductTypeId,productionType)
                .le(TaskEntity::getTaskStatus,VMSystem.TASK_STATUS_PROGRESS);
        return this.count(qw) > 0;
    }
    /**
     * 生成工单编号
     * @return
     */
    private String generateTaskCode(){
        //日期+序号
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));  //日期字符串
        String key= "lkd.task.code."+date; //redis key
        Object obj = redisTemplate.opsForValue().get(key);
        if(obj==null){
            redisTemplate.opsForValue().set(key,1L, Duration.ofDays(1) );
            return date+"0001";
        }
        return date+  Strings.padStart( redisTemplate.opsForValue().increment(key,1).toString(),4,'0');
    }

    /**
     * 功能描述: 接受工单
     * @param id
     * @return : boolean
     */
    @Override
    public boolean accept(Long id) {
        //工单校验(有没有)
        //判断工单类型
        //校验工单状态
        //设置执行人名称和ID
        //设置更新时间
        //分布式锁,防止高并发接单(复杂度高)
        TaskEntity task = this.getById(id);  //查询工单
        if(task.getTaskStatus()!= VMSystem.TASK_STATUS_CREATE ){
            throw new LogicException("工单状态不是待处理");
        }
        task.setTaskStatus( VMSystem.TASK_STATUS_PROGRESS );//修改工单状态为进行
        return this.updateById(task);
    }
    /**
     * 功能描述: 取消工单
     * @param id
     * @param cancelVM
     * @return : boolean
     */
    @Override
    public boolean cancelTask(Long id, CancelTaskViewModel cancelVM) {
        //工单校验(有没有)
        //判断工单类型
        //校验工单状态
        //判断当前登录人类型
        TaskEntity task = this.getById(id);  //查询工单
        if(task.getTaskStatus()== VMSystem.TASK_STATUS_FINISH  || task.getTaskStatus()== VMSystem.TASK_STATUS_CANCEL ){
            throw new LogicException("工单已经结束");
        }
        task.setTaskStatus( VMSystem.TASK_STATUS_CANCEL  );
        task.setDesc(cancelVM.getDesc());
        return this.updateById(task);
    }
    /**
     * 功能描述: 完成工单
     * @param id
     * @return : boolean
     */
    @Override
    public boolean completeTask(long id) {
        //校验id
        //判断工单类型
        //校验工单状态
        //判断当前登录人类型
        TaskEntity taskEntity = this.getById(id);
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_FINISH);//修改工单状态
        return this.updateById(taskEntity);

    }

    /**
     * 功能描述: 工单统计
     * @param beginTime
     * @param endTime
     * @return : com.lkd.http.vo.TaskReportInfoVO
     */
    @Override
    public List<TaskReportInfoVO> countTask(LocalDateTime beginTime, LocalDateTime endTime) {

        //运营工单总数
        var supplyTotal = this.taskCount(beginTime, endTime, false, null);
        //运维工单总数
        var repairTotal = this.taskCount(beginTime, endTime, true, null);
        //完成的运营工单总数
        var completedSupply = this.taskCount(beginTime,endTime,false,VMSystem.TASK_STATUS_FINISH);
        //取消的运营工单总数
        var cancelSupply = this.taskCount(beginTime,endTime,false,VMSystem.TASK_STATUS_CANCEL);
        //进行的运营工单总数
        var progressSupply =this.taskCount(beginTime,endTime,false,VMSystem.TASK_STATUS_PROGRESS);
        // 完成的运维工单总数
        var completedRepair = this.taskCount(beginTime,endTime,true,VMSystem.TASK_STATUS_FINISH);
        //取消的运维工单总数
        var cancelRepair = this.taskCount(beginTime,endTime,true,VMSystem.TASK_STATUS_CANCEL);
        //进行的运维工单总数
        var progressRepair = this.taskCount(beginTime,endTime,true,VMSystem.TASK_STATUS_PROGRESS);
        //运营的员工总数
        var operatorCount = userService.getOperatorCount();
        //运维的员工总数
        Integer repairerCount = userService.getRepairerCount();
        ArrayList<TaskReportInfoVO> result = Lists.newArrayList();
        //运营人员
        var supplyTaskInfo = new TaskReportInfoVO();
        supplyTaskInfo.setCompletedTotal(completedSupply);
        supplyTaskInfo.setCancelTotal(cancelSupply);
        supplyTaskInfo.setProgressTotal(progressSupply);
        supplyTaskInfo.setTotal(supplyTotal);
        supplyTaskInfo.setRepair(false);
        supplyTaskInfo.setWorkerCount(operatorCount);
        result.add(supplyTaskInfo);
        //运维人员
        var repairTaskInfo = new TaskReportInfoVO();
        repairTaskInfo.setCompletedTotal(completedRepair);
        repairTaskInfo.setCancelTotal(cancelRepair);
        repairTaskInfo.setProgressTotal(progressRepair);
        repairTaskInfo.setTotal(repairTotal);
        repairTaskInfo.setRepair(true);
        repairTaskInfo.setWorkerCount(repairerCount);
        result.add(repairTaskInfo);
        return result;
    }
    /**
     * 功能描述: 工单统计
     * @param beginTime
     * @param endTime
     * @param repair 是否是运维工单
     * @param taskStates
     * @return : int
     */
    private int taskCount(LocalDateTime beginTime, LocalDateTime endTime,Boolean repair, Integer taskStates){
        //日期字符串类型转LocalDate
        /*DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime start = LocalDateTime.parse(beginTime, formatter);
        LocalDateTime end = LocalDateTime.parse(endTime, formatter);*/
        //查询时间范围内工单--按工单状态查询
        LambdaQueryWrapper<TaskEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.between(TaskEntity::getUpdateTime,beginTime,endTime);
        if (taskStates != null){
            wrapper.eq(TaskEntity ::getTaskStatus,taskStates);
        }
        //如果是运维工单(ne--不等于)
        if (repair){
            wrapper.ne(TaskEntity ::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
        }else {
            wrapper.eq(TaskEntity ::getProductTypeId,VMSystem.TASK_TYPE_SUPPLY);
        }
       return this.count(wrapper);
    }
}
